import { Component, OnDestroy, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import {FormBuilder, FormGroup} from '@angular/forms';
import { Subscription } from 'rxjs/Rx';
import { MatDialog } from '@angular/material';
//import { MatSlider } from '@angular/slider';
import { RestService } from '../services/rest.service';
import { TranslateService } from '@ngx-translate/core';
import { PersonDetailsComponent } from './person-details/person-details.component';
//import { environment } from 'environments/environment';
import { PwizardComponents } from './pwizard/pwizard.component';
import { ListPersonComponents } from './list-person/list-person.component';

declare var BMap;
declare var BMapLib;
var map;
var thisme;
var att;

import * as _ from 'lodash';
@Component({
  templateUrl: './map.component.html',
  styleUrls: ['./map.component.css'],
})
export class MapComponent implements OnInit, OnDestroy {
  routeSubscription: Subscription;

  refreshInterval = 60 *1000;//environment.interval;
  refreshTask: any;

  personMarker=[];
  formGroup: FormGroup;

  displayedColumns: string[] = ['number', 'personName', 'building', 'level', 'room', 'bed', 'device1Id', 'nurseName', 'state', 'actions'];
  displayedColumnsDevice: string[] = ['number', 'deviceId', 'personName', 'updateTime'];
  institution: any;



  personTotal: any = '-';
  personAbnormal: any = '-';
  personNormal: any = '-';
  personAway: any = '-';

  deviceTotal: any = '-';
  deviceInUse: any = '-';
  deviceToUse: any = '-';
  deviceAbnormal: any = '-';

  abnormalPersonClass = 'inactive';
  normalPersonClass = 'inactive';
  allPersonClass = 'inactive';
  awayPersonClass = 'inactive';

  allDeviceClass = 'inactive';
  inUseDeviceClass = 'inactive';
  toUseDeviceClass = 'inactive';
  abnormalDeviceClass = 'inactive';

  showLoadingFlag = false;

  showAbnormalPerson = false;
  showNormalPerson = false;
  showAllPerson = false;
  showAwayPerson = false;

  showAllDevice = false;
  showInUseDevice = false;
  showToUseDevice = false;
  showAbnormalDevice = false;

  dataSource = [];


  showPersonDetails = false;
  person: any;
  selectPerson:any;
  personId:any;
  address:any;
  selectPosition:any;
  selectPoint:any;

  constructor(public dialog: MatDialog,
              private router: Router,
              private route: ActivatedRoute,
              private fb: FormBuilder,
              private translate: TranslateService,
              private rest: RestService) {
    this.institution = this.rest.getInstitution();
    this.person = {};
    this.selectPerson={};
    this.selectPosition =false;
    thisme = this;//this.person.kilo
    this.formGroup = fb.group({
      name: [
        { value: 0, disabled: false },
        [ ]
      ],
      firstName: [
        { value: this.person.device1Id, disabled: false },
        [ ]
      ]
    });
  }

  getBgClass() {
    return (this.showPersons() || this.showDevices() || this.showPersonDetails) ? 'hst-bg-blank' : 'hst-bg';
  }

  getListClass() {
    return this.showPersonDetails ? 'wdl-container-person' : 'wdl-container';
  }

  resetStaticsClass() {
    this.abnormalPersonClass = 'inactive';
    this.normalPersonClass = 'inactive';
    this.allPersonClass = 'inactive';
    this.awayPersonClass = 'inactive';
    this.allDeviceClass = 'inactive';
    this.inUseDeviceClass = 'inactive';
    this.toUseDeviceClass = 'inactive';
    this.abnormalDeviceClass = 'inactive';
  }

  navigateTo(item) {
    this.router.navigateByUrl('/map/' + item);
  }

  reset() {
    this.dataSource = [];

    this.showPersonDetails = false;

    this.showAbnormalPerson = false;
    this.showNormalPerson = false;
    this.showAllPerson = false;
    this.showAwayPerson = false;

    this.showAllDevice = false;
    this.showInUseDevice = false;
    this.showToUseDevice = false;
    this.showAbnormalDevice = false;
  }

  switchTable(table) {
    switch (table) {
    case 'allPerson':
      this.resetStaticsClass();
      if (this.showAllPerson) {
        this.showAllPerson = false;
        this.showPersonDetails = false;
        return;
      }

      this.reset();
      this.showAllPerson = true;
      this.allPersonClass = 'active';
      break;
    case 'normalPerson':
      this.resetStaticsClass();
      if (this.showNormalPerson) {
        this.showNormalPerson = false;
        this.showPersonDetails = false;
        return;
      }

      this.reset();
      this.showNormalPerson = true;
      this.normalPersonClass = 'active';
      break;
    case 'abnormalPerson':
      this.resetStaticsClass();
      if (this.showAbnormalPerson) {
        this.showAbnormalPerson = false;
        this.showPersonDetails = false;
        return;
      }

      this.reset();
      this.showAbnormalPerson = true;
      this.abnormalPersonClass = 'active';
      break;
    case 'awayPerson':
      this.resetStaticsClass();
      if (this.showAwayPerson) {
        this.showAwayPerson = false;
        this.showPersonDetails = false;
        return;
      }

      this.reset();
      this.awayPersonClass = 'active';
      this.showAwayPerson = true;
      break;
    case 'allDevice':
      this.resetStaticsClass();
      if (this.showAllDevice) {
        this.showAllDevice = false;
        return;
      }

      this.reset();
      this.showAllDevice = true;
      this.allDeviceClass = 'active';
      break;
    case 'inUseDevice':
      this.resetStaticsClass();
      if (this.showInUseDevice) {
        this.showInUseDevice = false;
        return;
      }

      this.reset();
      this.showInUseDevice = true;
      this.inUseDeviceClass = 'active';
      break;
    case 'toUseDevice':
      this.resetStaticsClass();
      if (this.showToUseDevice) {
        this.showToUseDevice = false;
        return;
      }

      this.reset();
      this.showToUseDevice = true;
      this.toUseDeviceClass = 'active';
      break;
    case 'abnormalDevice':
      this.resetStaticsClass();
      if (this.showAbnormalDevice) {
        this.showAbnormalDevice = false;
        return;
      }

      this.reset();
      this.showAbnormalDevice = true;
      this.abnormalDeviceClass = 'active';
      break;
    }

    this.fetchTableData();
  }

  showPersons() {
    return this.showAllPerson || this.showNormalPerson || this.showAbnormalPerson || this.showAwayPerson;
  }

  showDevices() {
    return this.showAllDevice || this.showAbnormalDevice || this.showInUseDevice || this.showToUseDevice;
  }

  hidePerson() {
    this.showPersonDetails = false;
  }

  openMonitor(row) {
    this.person = row;
    this.showPersonDetails = true;
  }

  openHist(row) {
    this.dialog.open(PersonDetailsComponent, {
      disableClose: true,
      autoFocus: false,
      width: '1200px',
      data: {
      //  person: row
      }
    });
  }

  getAlarmText(person) {
    const alarms = [];

    if (person.deviceAlarmFlag) {
      alarms.push(this.translate.get('DEVICE')['value']);
    }

    if (person.awayAlarmFlag) {
      alarms.push(this.translate.get('AWAY')['value']);
    }

    if (person.wetAlarmFlag) {
      alarms.push(this.translate.get('WET')['value']);
    }

    if (person.sideAlarmFlag) {
      alarms.push(this.translate.get('SIDE')['value']);
    }

    if (person.upAlarmFlag) {
      alarms.push(this.translate.get('UP')['value']);
    }

    if (person.heartAlarmFlag) {
      alarms.push(this.translate.get('HEART')['value']);
    }

    if (person.breatheAlarmFlag) {
      alarms.push(this.translate.get('BREATHE')['value']);
    }

    if (person.moveAlarmFlag) {
      alarms.push(this.translate.get('MOVE')['value']);
    }

    if (person.ringAlarmFlag) {
      alarms.push(this.translate.get('RING')['value']);
    }

    if (person.turnOverReminderAlarmFlag) {
      alarms.push(this.translate.get('TURN_OVER')['value']);
    }

    if (person.leftAlarmFlag) {
      alarms.push(this.translate.get('LEFT')['value']);
    }

    if (person.rightAlarmFlag) {
      alarms.push(this.translate.get('RIGHT')['value']);
    }

    if (alarms.length < 1) {
      return this.translate.get('normal')['value'];
    } else {
      return alarms.join(', ');
    }
  }

  convertData(items) {
    items.forEach(item => {
      if (item.bedString && item.bedString.indexOf('##') > -1) {
        const bedStrings = item.bedString.split('##');
        if (bedStrings.length > 0) {
          item['building'] = bedStrings[0];
        } else {
          item['building'] = '-';
        }

        if (bedStrings.length > 1) {
          item['level'] = bedStrings[1];
        } else {
          item['level'] = '-';
        }

        if (bedStrings.length > 2) {
          item['room'] = bedStrings[2];
        } else {
          item['room'] = '-';
        }

        if (bedStrings.length > 3) {
          item['bed'] = bedStrings[3];
        } else {
          item['bed'] = '-';
        }
      } else {
        item['building'] = '-';
        item['level'] = '-';
        item['room'] = '-';
        item['bed'] = '-';
      }
    });

    return items;
  }

  getAbnormalDeviceTime() {
    // Not updated for more than 1 minutes
    return new Date().getTime() - 1 * 60 * 1000;
  }

  fetchTableData() {
    let url;
    if (this.showAllPerson) {
      url = 'data/person/search/findallin';
    } else if (this.showNormalPerson) {
      url = 'data/person/search/findnormalin';
    } else if (this.showAbnormalPerson) {
      url = 'data/person/search/findabnormalin';
    } else if (this.showAwayPerson) {
      url = 'data/person/search/findawayin';
    } else if (this.showAllDevice) {
      url = 'data/device/search/findall';
    } else if (this.showAbnormalDevice) {
      url = 'data/device/search/findabnormal';
    } else if (this.showInUseDevice) {
      url = 'data/device/search/findinuse';
    } else if (this.showToUseDevice) {
      url = 'data/device/search/findtouse';
    }

    if (url) {
      this.showLoadingFlag = true;
      const parameters = {
        institutionId: this.institution.id
      };

      if (this.showAbnormalDevice) {
        parameters['updateTime'] = this.getAbnormalDeviceTime();
      }

      this.rest.getWithParams(url, parameters).subscribe(data => {
        this.processTableData(data['_embedded']);
        this.showLoadingFlag = false;
      }, () => {
        this.dataSource = [];
        this.showLoadingFlag = false;
      });
    } else {
      this.dataSource = [];
    }
  }

  processTableData(data) {
    if (this.showAllPerson || this.showNormalPerson || this.showAbnormalPerson || this.showAwayPerson) {
      this.dataSource = this.convertData(data['persons']);
    } else if (this.showAllDevice || this.showAbnormalDevice || this.showInUseDevice || this.showToUseDevice) {
      this.dataSource = data['devices'];
    }

    let itemNumber = 1;
    this.dataSource.forEach(item => {
      item['number'] = itemNumber++;
    });
  }

  refresh() {
    //console.log('refresh:'+this.refreshInterval);
    this.getDevices();
    if (this.rest.getCurrentApp() !== 'map') {
      return;
    }

    this.rest.getWithParams('api/pro/statistics', {institutionId: this.institution.id}).subscribe(resp => {
      this.personTotal = resp['countallin'];
      this.personNormal = resp['countnormalin'];
      this.personAway = resp['countawayin'];

      this.deviceTotal = resp['countall'];
      this.deviceInUse = resp['countinuse'];
      this.deviceAbnormal = resp['countabnormal'];

      this.personAbnormal = this.personTotal - this.personNormal;
      this.deviceToUse = this.deviceTotal - this.deviceInUse;
      this.scheduleNext();
    }, message => {
      console.error('Failed to retrieve data from server.');
      this.scheduleNext();
    });
  }

  scheduleNext() {
    if (this.rest.getCurrentApp() !== 'map') {
      return;
    }

    this.refreshTask = setTimeout(() => {
     /* if (this.rest.getCurrentApp() !== 'map') {
        return;
      }*/

      this.refresh();
    }, this.refreshInterval);
  }

  ngOnInit() {
    this.routeSubscription = this.route.params.subscribe(params => {
      const personId = params['person'];
      if (personId) {
        this.rest.getWithParams('/data/person/search/index', {index: personId}).subscribe(resp => {
          this.person = resp;
         // this.selectPerson = resp;
          this.showPersonDetails = true;
        });
      }
      this.ionViewDidLoad();
      this.refresh();
    });
  }

  ngOnDestroy() {
    if (this.refreshTask) {
      clearTimeout(this.refreshTask);
    }
  }

  checkin() {

    this.dialog.open(PwizardComponents, {
      disableClose: true,
      autoFocus: false,
      width: '330px',
      position: {right: '60px',top:'138px'},
      data: {
      //  person: row
      },
      //direction:"left"
    })
  }
  testclick(){
    this.rest.get('data/person/search/index?index='+this.personId).subscribe(data => {
      this.selectPerson = data;
       this.dialog.open(ListPersonComponents, {
         disableClose: true,
         autoFocus: false,
         width: '330px',
         position: {right: '60px',top:'138px'},
         data: {
           person: this.selectPerson
         },
         //direction:"left"
       }).afterClosed().subscribe(data => {
         if (!data || _.isString(data) || _.isEmpty(data)) {
           return;
         }
         //console.log(data);
       });
    });
  }
  add0(m){return m<10?'0'+m:m }
  dateformat(date)
  {
    var time = new Date(date);
    //var y = time.getFullYear();
    var m = time.getMonth()+1;
    var d = time.getDate();
    var h = time.getHours();
    var mm = time.getMinutes();
    // var s = time.getSeconds();
    return this.add0(m)+'-'+this.add0(d)+' '+this.add0(h)+':'+this.add0(mm);//+':'+add0(s);
  }
  personDetail(){
    const endTime = new Date().getTime() / 1000;
    const startTime = endTime - 60 * 60;
    const step = 5;

    this.rest.get('data/person/search/index?index='+this.personId).subscribe(data => {
      this.selectPerson = data;

      this.rest.getWithParams('api/v1/query_range', {
        query: 'breathe{personId="' + this.personId + '"}',
        start: startTime,
        end: endTime,
        step: step,
        timeout: 4
      }).subscribe(resp => {
        console.log(resp);
        if (resp['status'] === 'success') {
          let currentValue = 0;
          let currentDate =0;
          if (resp['data']['result'].length < 1) {
            currentValue = 0;
          }else {
            const data = resp['data']['result'][0].values;
            console.log(data);
            data.forEach(item => {
              item[0] = item[0] * 1000;
            });

            currentValue = data[data.length - 1][1];
            currentDate =  data[data.length - 1][0];
            /*if (currentValue.length === 1) {
              currentValue = '0' + currentValue;
            }*/
          }
          // if(currentValue==0){
          //  this.selectPerson.curbreathe = "--";
          // }else {
          this.selectPerson.curbreathe = currentValue;
          // }
          if(currentDate==0){
            this.selectPerson.breathedate = "----- -- -";
          }else {
            this.selectPerson.breathedate = this.dateformat(currentDate);
          }
          console.log("breathedate:"+this.selectPerson.curbreathe+","+this.selectPerson.breathedate);
        }
      });
      this.rest.get('api/influx/getHeartByPersonId?personId=' + this.personId).subscribe(pdata => {
        //console.log(pdata);
        this.selectPerson.heart = "--";
        this.selectPerson.hearttime = "-----";
        this.selectPerson.pressureH = "-";
        this.selectPerson.pressureL = "-";
        if(pdata!=null){
          this.selectPerson.heart = pdata[2];
          //var date = new Date(pdata[0]).toLocaleString();
          this.selectPerson.hearttime = this.dateformat(pdata[0]);
          this.selectPerson.pressureH = pdata[3];
          this.selectPerson.pressureL = pdata[4];
        }
        this.formGroup.setValue({
          name:    this.selectPerson.kilo,
          firstName: this.address
        });
        this.getAddressByGPS(this.selectPerson.longitude,this.selectPerson.latitude)
        var upmapdiv = document.getElementById('up-map-div');
        //console.log(upmapdiv);
        upmapdiv.setAttribute('style', 'width:330px;');
        var mPoint = new BMap.Point(this.selectPerson.longitude,this.selectPerson.latitude);
        //console.log(mPoint);
        var radius = this.selectPerson.kilo *1000;
        var circle = new BMap.Circle(mPoint,radius,{fillColor:"blue", strokeWeight: 1 ,fillOpacity: 0.3, strokeOpacity: 0.3});
        map.addOverlay(circle);
      },message=>{
        console.error('Failed to get Coordinate By PersonId in: ' + message);
      });

    });
  }
  getAddressByGPS(lng,lat){
    //120.328675,36.086094
    var geoc = new BMap.Geocoder();
    var pt = new BMap.Point(lng, lat);
    geoc.getLocation(pt, function(rs){
      //addressComponents对象可以获取到详细的地址信息
      var addComp = rs.addressComponents;
      var site = addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber;
      //将对应的HTML元素设置值
      //console.log(site);
      thisme.address = site;
      //console.log("经纬度："+pt.lng+","+pt.lat);
     // if(thisme.selectPosition) {
        thisme.selectPoint = pt;
        thisme.formGroup.setValue({
          name: thisme.selectPerson.kilo,
          firstName: thisme.address
        });
      //}
    });
  }
  closemapdiv(){
    var upmapdiv = document.getElementById('up-map-div');
    //console.log(upmapdiv);
    upmapdiv.setAttribute('style', 'width:330px;height:calc(100% - 50px);display:none;');
    att.className = att.className.replace('rightCurrent','');
    //console.log(att.className);
  }
  guardclick(){
    const data = {};
    const newkilo = this.formGroup.controls.name.value;
    data['kilo'] = newkilo;
    this.selectPerson.longitude = this.selectPoint.lng;
    this.selectPerson.latitude = this.selectPoint.lat;
    data['longitude'] = this.selectPerson.longitude;
    data['latitude'] = this.selectPerson.latitude;
    this.rest.patch( 'data/person/' + this.selectPerson.id, data).subscribe(resp => {
      console.log('update kilo info for ' + this.selectPerson.personName + ' successfully!');

    }, message => {
      this.rest.showHttpError('modifyPersonError', message);
      //this.refreshSearch();
    });
  }
  selectclick(){
    this.selectPosition = true;
  }
  listin(personId) {
    this.rest.get('data/person/search/index?index='+personId).subscribe(data => {
      this.selectPerson = data;
      this.dialog.open(ListPersonComponents, {
        disableClose: true,
        autoFocus: false,
        width: '330px',
        position: {right: '60px',top:'138px'},
        data: {
          person: this.selectPerson
        },
        //direction:"left"
      }).afterClosed().subscribe(data => {
        if (!data || _.isString(data) || _.isEmpty(data)) {
          return;
        }
        //console.log(data);
      });
    });
  }
  ionViewDidLoad() {

    //Amin: !Important:map_container shoud be called here, it can't be inited in constructor, if called in constructor

    map = new BMap.Map("mapContainer",{ enableMapClick: false });
  //  this.map.setMapStyle({
 //     styleJson:"/assets/custom_map_config.json"
  //    }
  //  );
    //map.centerAndZoom('青岛', 12);
    var point = new BMap.Point(120.358413,36.093695);  // 创建点坐标
    map.centerAndZoom(point, 12);

    map.enableScrollWheelZoom(true);

   // this.myGeo = new BMap.Geocoder();

    var geoc = new BMap.Geocoder();

    map.addEventListener("click", function(e){
      //通过点击百度地图，可以获取到对应的point, 由point的lng、lat属性就可以获取对应的经度纬度
      var pt = e.point;
      geoc.getLocation(pt, function(rs){
        //addressComponents对象可以获取到详细的地址信息
        var addComp = rs.addressComponents;
        var site = addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber;
        //将对应的HTML元素设置值
        //console.log(site);
        thisme.address = site;
        //console.log("经纬度："+pt.lng+","+pt.lat);
        if(thisme.selectPosition) {
          thisme.selectPoint = pt;
          thisme.formGroup.setValue({
            name: thisme.selectPerson.kilo,
            firstName: thisme.address
          });
        }
      });
    });

   // var geolocationControl = new BMap.GeolocationControl();

   // this.map.addControl(geolocationControl);

   //this.getLocation();

  //  this.getDevices();
    this.getDevices()
  }


getDevices(){

  var allOverlay = map.getOverlays();
  for(var j = 0;j<allOverlay.length;j++) {
    map.removeOverlay(allOverlay[j]);
  }

  this.rest.getWithParams('/data/device/search/allTypes', {
    institutionId: this.institution.id,
    //  page:0,
    //  size:50,
    // sort:'deviceId,asc',
    deviceType: "20%"
  }).subscribe(data => {
    //console.log(data);
    data['_embedded']['devices'].forEach(device => {
      //console.log(device.personId);
      this.rest.get('/api/influx/getCoordinateByPersonId?personId=' + device.personId).subscribe(pdata => {
        //console.log(pdata);
        if(pdata!=null) {
          this.getHeartAndMaker(pdata[2], pdata[3], device.personId, pdata[5]);
        }
      },message=>{
        console.error('Failed to get Coordinate By PersonId in: ' + message);
      });
    });
  },message=>{
    console.error('Failed to get all devices: ' + message);
  });

  }
 getHeartAndMaker(lng,lat,personId,personName){
  // this.devName = personName;
   this.rest.get('api/influx/getHeartByPersonId?personId=' + personId).subscribe(pdata => {
     //console.log(pdata);
     let heart = 0;
     if(pdata!=null){
       heart = pdata[2];
     }
     var sContent = '<div style="border-bottom:1px solid #ddd;font-size:12px;line-height:30px;">' + personName + '</div>'
       + '<div style="line-height:36px;"><img src="/assets/images/heart_small.png"> 心率<span style="float:right">' + heart + ' bpm</span></div>';
     //console.log(heart);
     this.addMapMaker(lng,lat,personId,sContent);
   },message=>{
     console.error('Failed to get Coordinate By PersonId in: ' + message);
   });
 }
 addMapMaker(lng,lat,personId,sContent){

    var point = new BMap.Point(lng, lat);

    var convertor = new BMap.Convertor();
    var pointArr = [];
    pointArr.push(point);
    convertor.translate(pointArr, 1, 5, function (data) {
      if(data.status === 0) {
        var opts = personId;
        var infoWindow = new BMap.InfoWindow(sContent,opts);//  创建信息窗口对象
        //var marker = new BMap.Marker(data.points[0]);
        var size = new BMap.Size(20, 26);  //图片尺寸
        var offset = new BMap.Size(0, -12);
        var imageSize = new BMap.Size(20, 26);
        var myIcon = new BMap.Icon("/assets/images/icon.png", size, {
          imageSize: imageSize
        });
        var marker = new BMap.Marker(data.points[0],{
          icon: myIcon,
          offset: offset
        });
        att = document.getElementById('userInfo');
        thisme.personMarker[personId] = marker;
        marker.addEventListener("click",function(e){
          thisme.personId =personId;
          this.openInfoWindow(infoWindow,point); //开启信息窗口
          //thisme.listin(personId);
          thisme.closemapdiv();
          att.className += ' rightCurrent';
        });
       /* marker.addEventListener("mouseover",function(e){
          this.openInfoWindow(infoWindow,point); //开启信息窗口

        });
        marker.addEventListener("mouseout",function (e) {
            this.closeInfoWindow();
        });*/
        map.addOverlay(marker);
      }
    });
 }

}
